const Promise = require('bluebird');

/**
 * 保存京东联盟订单
 */

// balanceName: ['未结算', '已结算']
// ynDetail: ['取消订单', '']
// ynName: ['无效', '有效']
// orderStatus: [1, 5]
// orderStatusName: ['已完成', '等待付款', '等待发货': 1, '等待出库', '锁定', '等待确认收货']

const statusMap = {'已完成': 1, '等待付款': 1, '等待发货': 1, '等待出库': 1, '锁定': 1, '等待确认收货': 1};
exports.save = function ({body, user_id}, {models: {Users, UserOrders, JDUserOrders, JDOrders, JDOrdersLogs, sequelize}, spider, config, wechatInstance}) {
    let {orderId} = body;
    if (!orderId) {
        return {success: false, messsage: '参数错误'};
    }

    let getOrderUrl = function () {
        return config.domain + '/partner_orders?orderId=' + orderId + '&type=jd';
    }
    return Users.findOne({where: {id: user_id, level: 'Partner'}}).then(function (partner) {
        if (!partner) {
            return {success: false, messsage: '没有权限'};
        }
        return JDOrders.findOne({where: {orderId: orderId}}).then(function (order) {
            if (order) {
                if (order.orderStatusName === body.orderStatusName) {
                    console.error('订单状态没有变', body);
                    return {success: true, exist: true};
                }
                if (order.ynDetail === '取消订单' || order.ynName === '无效') {
                    console.error('失效订单状态不能再更新了', body);
                    return {success: true, exist: true, messsage: '失效订单状态不能再更新了'};
                }

                if (!statusMap[body.orderStatusName]) {
                    wechatInstance.shopWebApi.sendText(partner.openid, '京东无效订单状态,' + body.orderStatusName, function (err) {
                        if (err) {
                            console.error('\n', err.stack || err.message);
                        }
                    });
                    return {success: true, messsage: '京东无效订单状态'};
                }

                return JDOrders.update(body, {where: {id: order.id}}).then(function (result) {
                    if (result[0]) {
                        JDOrdersLogs.create({
                            opt: 'StatusUpdate',
                            reference: order.id,
                            ext_data: JSON.stringify({
                                from: order.orderStatusName,
                                fromBy: order.postBy,
                                to: body.orderStatusName,
                                toBy: body.postBy
                            }),
                            user_id: user_id
                        });

                        if (body.ynDetail === '取消订单' || body.ynName === '无效') {
                            //is_back
                            JDOrders.backV2(order);

                            if (partner.notifyAllOrder && body.postBy != 'Import') {
                                wechatInstance.shopWebApi.sendText(partner.openid, order.orderId + '\n\n状态更新:' + order.orderStatusName + '-' + body.orderStatusName + '\n\n' + getOrderUrl(), function (err) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                });
                            }
                        }
                        if (body.orderStatusName === '已完成') {
                            //is_settle
                            JDOrders.settleV2(order);
                        }

                        return {success: true, update: true};
                    }

                    return {success: false, update: false, messsage: '状态更新失败'};
                });
            } else {
                let sql = "select * from Users where level in('Agency', 'Partner') and jd_pid = :jd_pid limit 0,1";
                return sequelize.query(sql, {
                    type: sequelize.QueryTypes.SELECT,
                    replacements: {jd_pid: body.spId}
                }).then(function (rows) {
                    return rows && rows[0];
                }).then(function (agency) {
                    if (agency && agency.inviter_id) {
                        return Users.findOne({
                            where: {id: agency.inviter_id, level: ['Agency', 'Partner']},
                            attributes: ['id']
                        }).then(function (inviterAgency) {
                            return {agency: agency, inviterAgency: inviterAgency}
                        });
                    }
                    return {agency: agency};
                }).then(function ({agency, inviterAgency}) {
                    if (agency) {
                        if (agency.agency_scale > 0) {
                            body.agency_id = agency.id;
                            body.agency_amount = (parseFloat(body.commission) * agency.agency_scale / 100).toFixed(2);
                        }
                        if (inviterAgency && agency.inviter_agency_scale > 0) {
                            body.inviter_agency_id = inviterAgency.id;
                            body.inviter_agency_amount = (parseFloat(body.commission) * agency.inviter_agency_scale / 100).toFixed(2);
                        }

                        if (agency.order_return_scale > 0) {
                            body.pay_amount = (parseFloat(body.commission) * agency.order_return_scale / 100).toFixed(2);
                        }
                        if (agency.inviter_scale > 0) {
                            body.inviter_pay_amount = (parseFloat(body.commission) * agency.inviter_scale / 100).toFixed(2);
                        }
                    }

                    body.partner_id = user_id;
                    return JDOrders.create(body).then(function (jdOrder) {
                        if (body.ynDetail != '取消订单' && body.ynName != '无效') {
                            JDUserOrders.findOne({where: {orderId: orderId}}).then(function (userOrder) {
                                if (!userOrder) {
                                    return;
                                }
                                return Users.findOne({where: {id: userOrder.user_id}}).then(function (user) {
                                    return JDUserOrders.update({status: 'Related'}, {where: {id: userOrder.id}}).then(function () {
                                        let updateData = {
                                            user_id: user.id,
                                            // pay_amount: spider.getRealFanli({
                                            //     fee: parseFloat(jdOrder.commission),
                                            //     user: user,
                                            //     agency: agency
                                            // }),
                                            status: 'Related'
                                        }
                                        if (user.inviter_id) {
                                            // && agency.inviter_scale > 0
                                            updateData.inviter_id = user.inviter_id;
                                            // updateData.inviter_pay_amount = (parseFloat(jdOrder.commission) * agency.inviter_scale / 100).toFixed(2);
                                        }
                                        return JDOrders.update(updateData, {where: {id: jdOrder.id}}).then(function () {
                                            return JDOrders.amountV2(jdOrder.id);
                                        });
                                    });
                                });
                            });

                            if (partner.notifyAllOrder && body.postBy != 'Import') {
                                wechatInstance.shopWebApi.sendText(partner.openid, jdOrder.orderId + '\n\n京东新订单:' + body.orderStatusName + '\n\n' + getOrderUrl(), function (err) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                });
                            }
                        }

                        return {success: true, create: true};
                    });
                });
            }
        });
    });

    return {success: true};
}